const mysql = require('mysql');
const YAML = require('yamljs');
const fs = require("fs");
// file为文件所在路径
const { db } = YAML.parse(fs.readFileSync('./config.yaml').toString());

// var Client = require('easymysql');
class DB {
    constructor(table,opt) {
        let _default = {
            host: db.host,
            user: db.user,
            password: db.password,
            port: 3306,
            database: db.database
        }
        let config = Object.assign({}, _default, opt)
            // this.conn = mysql.createConnection({
            //     host: db.host,
            //     user: db.user,
            //     password: db.password,
            //     database: db.database
            // });
            // this.$log('创建链接:',db);
        this.pool = mysql.createPool(config);
        this.table = table;
        this.data =[];
        return this;
    }
    $log(msg) {
        if (this._debug || db.debug) {
            console.log.apply(console, arguments);
        }
    }
    debug(flag){
         this._debug = flag;
        return this;
    }
    open(table) {
        this.$log('打开数据库');
        this.table = table;
        // this.conn.connect();
        return this;
    }
    close() {
        this.$log('关闭链接')
            // this.conn.end();
    }
    where(sql) {
        
        if(typeof sql =='string'){
            this.sql = `${this.sql}  && ${sql}`;
        }else{
            for (let item in sql) {
                this.where(`${item} = ?`)
                this.data.push(sql[item])
            }
        }
        
        return this;
    }
    or(sql) {
        this.sql = `${this.sql} or ${sql}`;
        return this;
    }
    appendSQL(sql) {
        this.sql = `${this.sql}  ${sql}`;
        return this;
    }
    insert(data) {
        this.data =[];
        let a = [],
            b = [];
        for (let item in data) {
            a.push(`${item}`)
            b.push(`?`)
            this.data.push(data[item])
        }
        //INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....)
        // `INSERT INTO  VALUES`
        this.sql = `INSERT INTO ${this.table}(
            ${a.join(',')}
        )  VALUES(
           ${b.join(',')}  
         ) `
        return this;
    }
    end() {
        this.$log('开始执行语句:', this.sql,this.data)
        return new Promise((resolve, reject) => {
            this.$log('开始链接:getConnection')
            this.pool.getConnection((err, conn) => {

                    if (err) {
                        reject(err, null, null);
                        this.$log('发生错误', err);
                        return;
                    }
                    conn.query(this.sql,this.data, (qerr, vals, fields) => {

                        if (qerr) {
                            reject(qerr, null, null);
                            this.$log('发生错误', qerr);
                            return;
                        }
                        this.$log('查询成功:', vals);
                        resolve(vals)
                        conn.release();
                        this.sql = '';
                    })
                })
                // this.conn.query(this.sql, (err, rows, fields) => {
                //         // this.$log(err)
                //         if (err) {
                //             this.$log(err)
                //             return err;
                //         }
                //         resolve(rows);
                //     })
                // this.close();
        })
    }
    update(data) {
        this.data =[];
        //UPDATE table_name SET field1=new-value1, field2=new-value2
        let value = [];
        
        for (let item in data) {
            value.push(`${item} = ?`)
            this.data.push(data[item])
        }
        this.sql = `UPDATE ${this.table}
         SET 
        ${value.join(',')}
          where 1=1 `
        return this
    }
    select(data){
        for (let item in data) {
            this.where(`${item} = ?`)
            this.data.push(data[item])
        }
        return this
    }  
    query(_sql) {
        this.data =[];
        if (_sql) {
            this.sql = `${_sql} where 1=1`
        } else {
            this.sql = `select * from ${this.table} where 1=1`
        }
        //  this.sql = _sql||`select * from ${this.table} where 1=1`  
        return this;
    }
}
module.exports = DB